﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Sac.Web;

public partial class Admin_MenuTreeManage : System.Web.UI.Page
{
    MenuTreeOperate rootClass = new MenuTreeOperate();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            btnDel.Attributes.Add("onclick", "return confirm('删除前请先确认该菜单无子菜单，否则无法删除！')");
            CreateMenuTree();
            CreateDropMenu();
            rbChild.Checked = true;
        }
    }

    protected void treeMenu_SelectedNodeChanged(object sender, EventArgs e)
    {
        string id_Key = treeMenu.SelectedNode.Value;
        MenuTree node = rootClass.GetMenuNodeById(id_Key);
        SetNodeInfo(node);
    }

    protected void rbRoot_CheckedChanged(object sender, EventArgs e)
    {
        if (rbRoot.Checked)
        {
            DropMenu.Enabled = false;
        }
        else
        {
            DropMenu.Enabled = true;
        } 
    }

    protected void btnSure_Click(object sender, EventArgs e)
    {
        MenuTree NewNode = new MenuTree();
        bool getSuccess = GetNodeInfo(NewNode);
        string script = "";
        if (getSuccess)
        {
            if (NewNode.ID_key == -1)
            {
                if (rootClass.InsertMenu(NewNode) == 1)
                {
                    InsertTreeMenu(NewNode, treeMenu.Nodes);
                    if (NewNode.Menu_Type != 2)
                        CreateDropMenu();
                    script = "alert('添加菜单成功！')";
                }
                else
                {
                    script = "alert('添加菜单失败！失败原因：" + rootClass.GetErrorMessage() + "')";
                }
            }
            else
            {
                bool isChild = false;
                if (NewNode.Menu_Type < 2)
                {
                    List<string> childList = new List<string>();
                    childList.Add(NewNode.ID_key.ToString());
                    rootClass.GetChildList(NewNode.ID_key.ToString(), childList);
                    foreach (string str in childList)
                    {
                        if (NewNode.FartherId == Convert.ToInt32(str))
                        {
                            isChild = true;
                            break;
                        }
                    }
                }
                if (!isChild)
                {
                    if (rootClass.UpdateMenu(NewNode) == 1)
                    {
                        TreeNode updateNode = treeMenu.SelectedNode;
                        UpdateTreeMenu(updateNode, NewNode);
                        script = "alert('修改菜单成功！')";
                    }
                    else
                    {
                        script = "alert('修改菜单失败！失败原因：" + rootClass.GetErrorMessage() + "')";
                    }
                }
                else
                {
                    script = "alert('菜单及其子孙菜单不能为其自身的父菜单！')";
                }
            }
            ClearInfo();
            ScriptManager.RegisterClientScriptBlock(UpdatePanel2, this.GetType(), "InsertOrUpdate", script, true);
        }       
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        string id_Key = tbID.Text.Trim();
        string script = "";
        if (id_Key != "")
        {
            int childCount = rootClass.GetChildCount(id_Key);
            if (childCount > 0)
            {
                script = "alert('删除失败！失败原因：该菜单包含子菜单。')";
                //ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "message", script, true);
                
            }
            else
            {
                if (rootClass.DeleteMenuNode(id_Key))
                {
                    DelelteDropItem(id_Key);
                    DeleteTreeMenu(id_Key, treeMenu.Nodes);
                    script = "alert('删除成功！')";
                }
                else
                {
                    script = "alert('删除失败！失败原因：" + rootClass.GetErrorMessage() + "')";
                }
            }
            ScriptManager.RegisterClientScriptBlock(UpdatePanel2, this.GetType(), "hasChildMenu", script, true);
        }
        ClearInfo();
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        ClearInfo();
    }

    protected void ClearInfo()
    {
        tbID.Text = "";
        tbMenuName.Text = "";
        tbMenuUrl.Text = "";
        tbMenuImgUrl.Text = "";
        tbMenuImgExpand.Text = "";
        rbRoot.Checked = false;
        rbChild.Checked = true;
        rbLeaf.Checked = false;
        rbRoot.Enabled = true;
        rbChild.Enabled = true;
        rbLeaf.Enabled = true;
        DropMenu.SelectedIndex = 0;
        DropMenu.Enabled = true;
        tb_Sort.Text = "0";
        tb_Power.Text = "0";
        btnDel.Enabled = false;
    }

    protected void SetNodeInfo(MenuTree nodeInfo)
    {
        tbID.Text = nodeInfo.ID_key.ToString();
        tbMenuName.Text = nodeInfo.Menu_Name;
        tbMenuUrl.Text = nodeInfo.Menu_Url;
        tbMenuImgUrl.Text = nodeInfo.Menu_Img_Url;
        tbMenuImgExpand.Text = nodeInfo.Menu_Img_Expand;
        switch (nodeInfo.Menu_Type)
        {
            case 0:
                rbRoot.Checked = true;
                rbChild.Checked = false;
                rbLeaf.Checked = false;
                break;
            case 1:
                rbRoot.Checked = false;
                rbChild.Checked = true;
                rbLeaf.Checked = false;
                break;
            case 2:
                rbRoot.Checked = false;
                rbChild.Checked = false;
                rbLeaf.Checked = true;
                break;
        }
        rbRoot.Enabled = false;
        rbChild.Enabled = false;
        rbLeaf.Enabled = false;
        try
        {
            DropMenu.SelectedValue = nodeInfo.FartherId.ToString();
            DropMenu.Enabled = true;
        }
        catch
        {
            DropMenu.SelectedIndex = 0;
            DropMenu.Enabled = false;
        }
        tb_Sort.Text = nodeInfo.Menu_Sort.ToString();
        tb_Power.Text = nodeInfo.Menu_Power_Id.ToString();
        btnDel.Enabled = true;
    }

    protected bool GetNodeInfo(MenuTree NewNode)
    {
        if (tbID.Text != "")
            NewNode.ID_key = Convert.ToInt32(tbID.Text.Trim());
        else
            NewNode.ID_key = -1;
       
        NewNode.Menu_Name = tbMenuName.Text.Trim();
        NewNode.Menu_Url = tbMenuUrl.Text.Trim();
        NewNode.Menu_Img_Url = tbMenuImgUrl.Text.Trim();
        NewNode.Menu_Img_Expand = tbMenuImgExpand.Text.Trim();
        if (rbRoot.Checked)
            NewNode.Menu_Type = 0;
        else if (rbChild.Checked)
            NewNode.Menu_Type = 1;
        else
            NewNode.Menu_Type = 2;
        try
        {
            if (NewNode.Menu_Type == 0)
                NewNode.FartherId = -1;
            else
                NewNode.FartherId = Convert.ToInt32(DropMenu.SelectedValue);
        }
        catch
        {
            ScriptManager.RegisterClientScriptBlock(UpdatePanel2, this.GetType(), "GetInfo", "alert('请选择父菜单！')", true);
            return false;
        }
        NewNode.Menu_Sort = Convert.ToInt32(tb_Sort.Text);
        NewNode.Menu_Power_Id = Convert.ToInt32(tb_Power.Text);
        return true;
    }

    protected void DeleteTreeMenu(string id_Key, TreeNodeCollection treeList)
    {
        foreach (TreeNode node in treeList)
        {
            if (node.Value == id_Key)
            {
                treeList.Remove(node);
                return;
            }
            DeleteTreeMenu(id_Key, node.ChildNodes);
        }
    }

    protected void InsertTreeMenu(MenuTree menuNode, TreeNodeCollection treeList)
    {
        TreeNode newTreeNode = new TreeNode();
        newTreeNode.Text = menuNode.Menu_Sort.ToString() + "|"
            + menuNode.Menu_Name.ToString() + "|" + menuNode.Menu_Power_Id.ToString();
        newTreeNode.Value = menuNode.ID_key.ToString();
        //newTreeNode.ImageUrl = menuNode.Menu_Img_Url;
        newTreeNode.SelectAction = TreeNodeSelectAction.Select;
        if (menuNode.FartherId == -1)
        {
            int index=0;
            foreach (TreeNode node in treeMenu.Nodes)
            {
                if (menuNode.Menu_Sort < Convert.ToInt32(node.Text.Split('|')[0]))
                    break;
                index++;
            }
            treeMenu.Nodes.AddAt(index, newTreeNode);
        }
        else
        {
            foreach (TreeNode node in treeList)
            {
                if (Convert.ToInt32(node.Value) == menuNode.FartherId)
                {
                    node.ChildNodes.Add(newTreeNode);
                    SortTreeMenuNode(newTreeNode);
                    return;
                }
                InsertTreeMenu(menuNode, node.ChildNodes);
            }
        }
    }

    protected void UpdateTreeMenu(TreeNode updateNode,MenuTree newNode)
    {
        int oldIndex = Convert.ToInt32(updateNode.Text.Split('|')[0]);
        updateNode.Text = newNode.Menu_Sort.ToString() + "|" + newNode.Menu_Name + "|" + newNode.Menu_Power_Id;
        //updateNode.ImageUrl = newNode.Menu_Img_Url;
        if (newNode.Menu_Type != 0)
        {
            int oldParent = Convert.ToInt32(updateNode.Parent.Value);
            TreeNode parent = updateNode.Parent;
            bool needSort = false;
            int i = 1;
            if (oldParent != newNode.FartherId)
            {
                GetNewParentNode(newNode.FartherId.ToString(), ref parent, treeMenu.Nodes);
                //parent.ChildNodes.Add(updateNode);
                i = 0;
                needSort = true;
            }
            if (oldIndex != newNode.Menu_Sort)
            {
                needSort = true;
            }
            if (needSort)
            {
                int index = 0;
                foreach (TreeNode node in parent.ChildNodes)
                {
                    if (Convert.ToInt32(updateNode.Text.Split('|')[0]) >= Convert.ToInt32(node.Text.Split('|')[0]))
                    {
                        index++;
                    }
                    else
                    {
                        break;
                    }
                }
                parent.ChildNodes.AddAt(index - i, updateNode);
                CreateDropMenu();
            }
        }
        else
        {
            if (oldIndex != newNode.Menu_Sort)
            {
                TreeNodeCollection tnc = treeMenu.Nodes;
                int index = 0;
                foreach (TreeNode node in tnc)
                {
                    if (Convert.ToInt32(updateNode.Text.Split('|')[0]) >= Convert.ToInt32(node.Text.Split('|')[0]))
                    {
                        index++;
                    }
                    else
                    {
                        break;
                    }
                }
                tnc.AddAt(index - 1, updateNode);
                CreateDropMenu();
            }
        }
    }

    protected void GetNewParentNode(string parentValue,ref TreeNode parent,TreeNodeCollection nodeList)
    {
        foreach (TreeNode node in nodeList)
        {
            if (node.Value == parentValue)
            {
                parent = node;
                return;
            }
            GetNewParentNode(parentValue,ref parent, node.ChildNodes);
        }
    }

    protected void SortTreeMenuNode(TreeNode sortNode)
    {
        TreeNodeCollection brothers = sortNode.Parent.ChildNodes;
        foreach (TreeNode node in brothers)
        {
            if (node.Value == sortNode.Value)
            {
                brothers.Remove(node);
                break;
            }
        }
        int index = 0;
        foreach (TreeNode node in brothers)
        {
            int sortNumber = Convert.ToInt32(sortNode.Text.Split('|')[0]);
            int idKey = Convert.ToInt32(sortNode.Value);
            int compareNumber = Convert.ToInt32(node.Text.Split('|')[0]);
            int compareIdKey = Convert.ToInt32(node.Value);
            if (sortNumber > compareNumber)
            {
                index++;
                continue;
            }
            else if (sortNumber == compareNumber)
            {
                if (idKey > compareNumber)
                {
                    index++;
                    continue;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        brothers.AddAt(index, sortNode);
    }

    protected void DelelteDropItem(string id_Key)
    {
        foreach (ListItem listNode in DropMenu.Items)
        {
            if (listNode.Value == id_Key)
            {
                DropMenu.Items.Remove(listNode);
                return;
            }
        }
    }


    protected void CreateMenuTree()
    {
        DataTable dtMenuList = rootClass.GetAllMenuNode();
        treeMenu.Nodes.Clear();
        InitTree(treeMenu.Nodes, "-1", dtMenuList);
    }

    protected void CreateDropMenu()
    {
        DataTable dtMenuList = rootClass.GetNonleafNodes();
        int i = -1;
        DropMenu.Items.Clear();
        ListItem li = new ListItem("———————请选择父菜单———————");
        DropMenu.Items.Add(li);
        InitDropMenu(dtMenuList, "-1", ref i);
    }

    protected void InitTree(TreeNodeCollection treeNodes, string fartherId, DataTable dtAllMenuNode)
    {
        DataView dv = new DataView();
        dv.Table = dtAllMenuNode;
        dv.RowFilter = "fartherid=" + fartherId;
        foreach (DataRowView drv in dv)
        {
            TreeNode node = new TreeNode();
            node.Value = drv["ID_KEY"].ToString();
            node.Text = drv["MENU_SORT"].ToString() + "|" + drv["MENU_NAME"].ToString() + "|" + drv["MENU_POWER_ID"].ToString();
            //if (drv["MENU_IMG_URL"].ToString() != "")
            //    node.ImageUrl = "~/" + drv["MENU_IMG_URL"].ToString();
            node.SelectAction = TreeNodeSelectAction.Select;
            treeNodes.Add(node);
            InitTree(node.ChildNodes, node.Value, dtAllMenuNode);
        }
    }

    protected void InitDropMenu(DataTable dtMenuList, string fartherId, ref int i)
    {
        i++;
        string str = "";
        for (int j = 0; j < i; j++)
        {
            if (j == 0)
            {
                str += "|—>";
            }
            else
            {
                str += "—>";
            }
        }
        string value = "";
        DataView dv = new DataView();
        dv.Table = dtMenuList;
        dv.RowFilter = "FartherID=" + fartherId + "";
        foreach (DataRowView drv in dv)
        {
            value = drv["ID_KEY"].ToString();
            ListItem li = new ListItem(str + drv["MENU_NAME"].ToString(), value);
            DropMenu.Items.Add(li);
            InitDropMenu(dtMenuList, drv["ID_KEY"].ToString(), ref i);
            i--;
        }
    }
}
